using AutoMapper;
using Core.SimpleTemp.Common;
using Core.SimpleTemp.Common.PagingQuery;
using Core.SimpleTemp.Entitys;
using Core.SimpleTemp.Repositories;
using Core.SimpleTemp.Repositories.Internal;
using Core.Toolkit.Common;
using Core.Toolkit.Core;
using Core.Toolkit.Core.Api;
using Core.Toolkit.Core.Application;
using Core.Toolkit.Core.Model;
using Core.Toolkit.Core.Repositories;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;

namespace Core.SimpleTemp.Application
{
    [AutoDi()]
    public class JG_STOPObserveMainService : BaseAppService<JG_STOPObserveMainDto, JG_STOPObserveMain, JG_STOPObserveMainRepository>
    {
        readonly ExcelHelp _excelHelp;
        readonly UserIdentity _userIdentity;
        readonly JG_STOPBigTypeRepository _bigTypeRepository;
        readonly JG_STOPSmallTypeRepository _smallTypeRepository;
        readonly JG_STOPObserveDetailRepository _detailRepository;
        readonly SQLHelper _sqlHelper;
        readonly CoreDBContext _coreDBContext;
        public JG_STOPObserveMainService(CoreDBContext coreDbContext, SQLHelper sqlHelper,JG_STOPObserveMainRepository repository,JG_STOPObserveDetailRepository detailRepository,JG_STOPBigTypeRepository bigTypeRepository,JG_STOPSmallTypeRepository smallTypeRepository, ExcelHelp excelHelp) : base(repository)
        {
            _excelHelp = excelHelp;
            this._bigTypeRepository = bigTypeRepository;
            this._smallTypeRepository = smallTypeRepository;
            this._detailRepository = detailRepository;
            this._sqlHelper = sqlHelper;
            this._coreDBContext = coreDbContext;

        }

        /// <summary>
        /// 获取已部门为层级的用户数据
        /// </summary>
        /// <returns></returns>
        public DataTable GetData(Guid? factoryId)
        {
            var factoryStr = "'"+((Guid)factoryId).ToString()+"'";
            var factory = _coreDBContext.SysFactory.FirstOrDefault(x => x.Id == factoryId);
            if (factory.FactoryType == "1")
            {
                factoryStr = "";
            }
            else
            {
                factoryStr = "where D.CreateFactory="+factoryStr+" and ui.workcompany=" + factoryStr;
            }
            
            //用户信息与部门信息UnionAll成数据集，（把用户信息当初部门子数据处理）
            string sql = @"SELECT  * FROM (SELECT   UI.SysUserID id,ui.Name label ,d.Id ParentId ,1 AS T FROM  SysDepartment D 
                            inner JOIN SysDepartmentDuty  DD ON  D.Id= DD.SysDepartmentID  
                            inner JOIN SysUserDuty  UD ON DD.Id=UD.SysDepartmentDutyId
                            inner JOIN  SysUser U  ON  UD.SysUserId =U.Id
                            inner Join SysUserInfor ui on  u.Id=ui.SysUserID " + factoryStr + @" ) AS TABLE1 group by TABLE1.id,TABLE1.label,TABLE1.ParentId,table1.T 
                            UNION ALL
                            select  ID,Name label ,ParentId ,0 AS T from SysDepartment";
            //查询
            var dataTable = _sqlHelper.ExecuteDataTable(sql, null);
            //移除没有用户的部门信息
            ChangeData(ref dataTable);
            return dataTable;
        }
        /// <summary>
        /// 移除没有用户的部门信息
        /// </summary>
        /// <param name="dataTable"></param>
        private void ChangeData(ref DataTable dataTable)
        {
            //查询出部门数据
            var rowDepartmentList = dataTable.Select("T=0");
            //保存没有用户的部门ID
            var noSubdataList = new List<object>();

            //查询出没有用户的部门ID
            foreach (var item in rowDepartmentList)
            {
                var noSubDataId = item["id"];
                var subdata = dataTable.Select("parentId='" + Convert.ToString(noSubDataId) + "'");
                if (subdata == null || !subdata.Any())
                    noSubdataList.Add(noSubDataId);
            }
            //移除没有用户的部门信息
            for (int i = dataTable.Rows.Count - 1; i >= 0; i--)
            {
                if (noSubdataList.Contains(dataTable.Rows[i]["id"]))
                    dataTable.Rows.RemoveAt(i);
            }


        }


        private LoadPageOffsetModelAuto<JG_STOPObserveMain, JG_STOPObserveMainDto>
            GetLoadPageOffsetMode(PagingModel<JG_STOPObserveMainDto>
                pagingQueryModel)
        {
            var loadPageOffsetModel = this.GetLoadPageOffsetModelAuto(pagingQueryModel);
            var baseQuery = _repository.QueryBase().AsNoTracking();
            loadPageOffsetModel.QueryWhere = this.CreateQRList()
                .Add("CreateFactory", "=")//工厂
                .Add("observePeople", "=")//观察人
                .Add("observation", "=")//观察时间
                .Add("department", "=")//部门
                .Add("shifts", "=")//班次
                .Add("situation", "=")
                .Add("observaDate", ">=", getTime(pagingQueryModel.Model.ObservationtimeStart, "b"))
                .Add("observaDate", "<", getTime(pagingQueryModel.Model.ObservationtimeEnd, "c"));
               
            if (loadPageOffsetModel.Model.evaluationc != null)
            {
                loadPageOffsetModel.QueryWhere.Add("evaluationc", "=");

            }
            //if(loadPageOffsetModel.Model.CreateFactory != null)




            //.Add("observaDate", ">=",getTime(pagingQueryModel.Model.ObservationtimeStart, "b"))
            //.Add("observaDate", "<", getTime(pagingQueryModel.Model.ObservationtimeEnd,"c"))
            //.Add("observePeople", "=") //观察人
            //.Add("shifts", "=") //班次
            //.Add("situation", "="); //区域
            loadPageOffsetModel.BasqQuery = baseQuery;
            //按工厂过滤
            //loadPageOffsetModel.BasqQuery = baseQuery.OrderByDescending(x => x.CreateTime).Where(y => y.CreateFactory == _userIdentity.Factory);

            loadPageOffsetModel.Order = orderModel => orderModel.CreateTime;

            //loadPageOffsetModel.Selector = model => new JG_STOPObserveMain()
            //{
            //    Id = model.Id,
            //    evaluationc = model.evaluationc,//所有皆安全
            //    department = model.department,//部门
            //    observePeople = model.observePeople,//观察人
            //    observaDate = model.observaDate,//观察日期
            //    observation = model.observation,//观察时间
            //    shifts = model.shifts,//班次
            //    situation = model.situation,//区域
            //    encourage = model.encourage,//安全行为
            //    correct = model.correct,//不安全行为
            //    State = model.State,//状态
            //    CreateFactory = model.CreateFactory,//隶属工厂
            //    CreateDept = model.CreateDept,//添加部门
            //    UpdateDept = model.UpdateDept,//更改部门
            //    ryfy_remark = model.ryfy_remark,//人员反映备注
            //    grfhzb_remark = model.grfhzb_remark,//个人防护装备备注
            //    rydwz_remark = model.rydwz_remark,//人员的位子备注
            //    gjjsb_remark = model.gjjsb_remark,//工具及设备备注
            //    cx_remark = model.cx_remark,//程序备注
            //    zxbz_remark = model.zxbz_remark,//秩序标准秩序标准
            //    ryfy_IsSafety = model.ryfy_IsSafety,//人员反映其他是否安全
            //    grfhzb_IsSafety = model.grfhzb_IsSafety,//个人防护装备是否安全
            //    rydwz_IsSafely = model.rydwz_IsSafely,//人员的位置是否安全
            //    jjsb_IsSafely = model.jjsb_IsSafely,//工具及设备是否安全
            //    cx_IsSafely = model.cx_IsSafely,//程序是否安全
            //    zxbz_IsSafely = model.zxbz_IsSafely,//秩序标准
            //};
            return loadPageOffsetModel;
        }

        public List<JG_STOPObserveMain> GetMainSourceData(DateTime? startDate, DateTime? endDate)
        {
            var result = _repository.QueryBase().Where(x=>x.observaDate>=startDate && x.observaDate<=endDate).ToList();
            return result;
        }

        public async Task<IPageModel<JG_STOPObserveMainDto>> GetList(PagingModel<JG_STOPObserveMainDto>
            pagingQueryModel)
        {
            var loadPageOffsetModel = GetLoadPageOffsetMode(pagingQueryModel);
            return await base.LoadPageOffsetAsync(loadPageOffsetModel);
        }
        public async Task<string>
           ExportStatistic(PagingModel<JG_STOPObserveMainDto>
               pagingQueryModel)
        {
            const string FILE_NAME_PREFIX = "STOP安全观察与沟通结果统计表";

            if (pagingQueryModel.Model.ObservationtimeStart != null)
            {
                pagingQueryModel.Model.ObservationtimeStart = ((DateTime)pagingQueryModel.Model.ObservationtimeStart).ToLocalTime().Date;
            }
            if (pagingQueryModel.Model.ObservationtimeEnd != null)
            {
                pagingQueryModel.Model.ObservationtimeEnd = ((DateTime)pagingQueryModel.Model.ObservationtimeEnd).ToLocalTime().Date;
            }
            var loadPageOffsetModel = GetLoadPageOffsetMode(pagingQueryModel);
            var DataList = await this.ExportDataAsync(loadPageOffsetModel);
            var smallTypes = this.GetSmallTypeList();

            foreach (var i in DataList)
            {
                i.observaDateText = ((DateTime)i.observaDate).ToShortDateString();
                i.ryfy_remark = "";
                i.grfhzb_remark = "";
                i.rydwz_remark = "";
                i.gjjsb_remark = "";
                i.cx_remark = "";
                i.zxbz_remark = "";
                List<JG_STOPObserveDetailDto> details = this.GetDetailList(i.Id).Where(x => x.IsNotSafe == true).ToList();
                var detailGroup = details.GroupBy(x => x.BigType);
                foreach (var d in detailGroup)
                {
                    switch (d.Key)
                    {
                        case "BT01":
                            {
                                foreach (var st in d)
                                {
                                    if (st.remark == "Custom1" || st.remark == "Custom2")
                                    {
                                        i.ryfy_remark += st.SmallType + ";";
                                    }
                                    else
                                    {
                                        i.ryfy_remark += smallTypes.FirstOrDefault(x => x.SmallTypeCode == st.SmallType).SmallTypeName + ";";
                                    }
                                }
                                break;
                            }
                        case "BT02":
                            {
                                foreach (var st in d)
                                {
                                    if (st.remark == "Custom1" || st.remark == "Custom2")
                                    {
                                        i.grfhzb_remark += st.SmallType + ";";
                                    }
                                    else
                                    {
                                        i.grfhzb_remark += smallTypes.FirstOrDefault(x => x.SmallTypeCode == st.SmallType).SmallTypeName + ";";
                                    }
                                }
                                break;
                            }
                        case "BT03":
                            {
                                foreach (var st in d)
                                {
                                    if (st.remark == "Custom1" || st.remark == "Custom2")
                                    {
                                        i.rydwz_remark += st.SmallType + ";";
                                    }
                                    else
                                    {
                                        i.rydwz_remark += smallTypes.FirstOrDefault(x => x.SmallTypeCode == st.SmallType).SmallTypeName + ";";
                                    }
                                }
                                break;
                            }
                        case "BT04":
                            {
                                foreach (var st in d)
                                {
                                    if (st.remark == "Custom1" || st.remark == "Custom2")
                                    {
                                        i.gjjsb_remark += st.SmallType + ";";
                                    }
                                    else
                                    {
                                        i.gjjsb_remark += smallTypes.FirstOrDefault(x => x.SmallTypeCode == st.SmallType).SmallTypeName + ";";
                                    }
                                }
                                break;
                            }
                        case "BT05":
                            {
                                foreach (var st in d)
                                {
                                    if (st.remark == "Custom1" || st.remark == "Custom2")
                                    {
                                        i.cx_remark += st.SmallType + ";";
                                    }
                                    else
                                    {
                                        i.cx_remark += smallTypes.FirstOrDefault(x => x.SmallTypeCode == st.SmallType).SmallTypeName + ";";
                                    }
                                }
                                break;
                            }
                        case "BT06":
                            {
                                foreach (var st in d)
                                {
                                    if (st.remark == "Custom1" || st.remark == "Custom2")
                                    {
                                        i.zxbz_remark += st.SmallType + ";";
                                    }
                                    else
                                    {
                                        i.zxbz_remark += smallTypes.FirstOrDefault(x => x.SmallTypeCode == st.SmallType).SmallTypeName + ";";
                                    }
                                }
                                break;
                            }
                        default: break;
                    }
                }
            }


            foreach (var i in DataList)
            {
                if (i.evaluationc != null && i.evaluationc == true)
                {
                    i.evaluationText = "是";
                }
                else
                {
                    i.evaluationText = "否";
                }


            }

            //summary
            pagingQueryModel.Offset = 0;
            pagingQueryModel.Limit = 999;

            IPageModel<JG_STOPObserveMainDto> data = await this.GetList(pagingQueryModel);
            var sourceData = data.PageData;

            int ryfysafe = sourceData.Count(x => x.ryfy_IsSafety == true);
            int ryfyunsafe = sourceData.Count(x => x.ryfy_IsSafety == false);

            int grfhzbsafe = sourceData.Count(x => x.grfhzb_IsSafety == true);
            int grfhzbunsafe = sourceData.Count(x => x.grfhzb_IsSafety == false);

            int rydwzsafe = sourceData.Count(x => x.rydwz_IsSafety == true);
            int rydwzunsafe = sourceData.Count(x => x.rydwz_IsSafety == false);

            int gjjsbsafe = sourceData.Count(x => x.gjjsb_IsSafety == true);
            int gjjsbunsafe = sourceData.Count(x => x.gjjsb_IsSafety == false);

            int cxsafe = sourceData.Count(x => x.cx_IsSafety == true);
            int cxunsafe = sourceData.Count(x => x.cx_IsSafety == false);

            int zxbzsafe = sourceData.Count(x => x.zxbz_IsSafety == true);
            int zxbzunsafe = sourceData.Count(x => x.zxbz_IsSafety == false);

            var summary = new
            {
                sum = "合计",
                text1 = "",
                text2 = "",
                text3 = "",
                ryfy = "安全:" + ryfysafe + " 不安全:" + ryfyunsafe,
                grfhzb = "安全:" + grfhzbsafe + " 不安全:" + grfhzbunsafe,
                rydwz = "安全:" + rydwzsafe + " 不安全:" + rydwzunsafe,
                gjjsb = "安全:" + gjjsbsafe + " 不安全:" + gjjsbunsafe,
                cx = "安全:" + cxsafe + " 不安全:" + cxunsafe,
                zxbz = "安全:" + zxbzsafe + " 不安全:" + zxbzunsafe,
            };

            JG_STOPObserveMainDto sumdto = new JG_STOPObserveMainDto();
            sumdto.observaDateText = "合计";
            
            sumdto.shiftsText = "";
            sumdto.observePeopleText = "";
            sumdto.correct = "";
            sumdto.ryfy_remark = summary.ryfy;
            sumdto.grfhzb_remark = summary.grfhzb;
            sumdto.rydwz_remark = summary.rydwz;
            sumdto.gjjsb_remark = summary.gjjsb;
            sumdto.cx_remark = summary.cx;
            sumdto.zxbz_remark = summary.zxbz;
            DataList.Add(sumdto);



            var excelData = DataList.Select(model => new
            {
                model.observaDateText,
                observaDateText_title = "观察日期",
                model.shiftsText,
                shiftsText_title = "班次",
                model.observePeopleText,
                observePeopleText_title = "观察者",
                model.correct,
                correct_title="不安全行为描述",
                model.ryfy_remark,
                ryfy_remark_title = "人员的反应",
                model.grfhzb_remark,
                grfhzb_remark_title = "个人防护装备",
                model.rydwz_remark,
                rydwz_remark_title = "人员的位置",
                model.gjjsb_remark,
                gjjsb_remark_title = "工具及设备",
                model.cx_remark,
                cx_remark_title = "程序",
                model.zxbz_remark,
                zxbz_remark_title = "秩序标准"


            }).ToList();
            

            //excelData.Add(new
            //{
            //    summary.sum,
            //    sum_title = "观察日期",
            //    summary.text1,
            //    text1_remark = "班次",
            //    summary.text2,
            //    text2_title = "观察者",
            //    summary.text3,
            //    text3_title="不安全行为描述",
            //    summary.ryfy,
            //    ryfy_title="人员的反应",
            //    summary.grfhzb,
            //    grfhzb_title="个人防护装备",
            //    summary.rydwz,
            //    rydwz_title="人员的位置",
            //    summary.gjjsb,
            //    gjjsb_title="工具及设备",
            //    summary.cx,
            //    cx_title="程序",
            //    summary.zxbz,
            //    zxbz_title="秩序标准"


            //});


            var fileName = FILE_NAME_PREFIX +DateTime.Now.Year+"_"+DateTime.Now.Month+"_"+DateTime.Now.Day+"_"+ TempDirHelp.GetTimeStampFielName(".xlsx");


            return _excelHelp.Create(excelData,fileName);
        }
        

        public async Task<string>
            Export(PagingModel<JG_STOPObserveMainDto>
                pagingQueryModel)
        {
            const string FILE_NAME_PREFIX = "STOP安全观察";
            
            if (pagingQueryModel.Model.ObservationtimeStart != null)
            {
                pagingQueryModel.Model.ObservationtimeStart = ((DateTime)pagingQueryModel.Model.ObservationtimeStart).ToLocalTime().Date;
            }
            if (pagingQueryModel.Model.ObservationtimeEnd != null)
            {
                pagingQueryModel.Model.ObservationtimeEnd = ((DateTime)pagingQueryModel.Model.ObservationtimeEnd).ToLocalTime().Date;
            }
            var loadPageOffsetModel = GetLoadPageOffsetMode(pagingQueryModel);
            var DataList = await this.ExportDataAsync(loadPageOffsetModel);
            foreach (var i in DataList)
            {
                if (i.evaluationc != null && i.evaluationc == true)
                {
                    i.evaluationText = "是";
                }
                else
                {
                    i.evaluationText = "否";
                }


            }
            var excelData = DataList.Select(model => new
            {
                model.observePeopleText,
                observePeopleText_title = "观察人",
                model.observation,
                observation_title = "观察时间(分钟)",
                model.shiftsText,
                shiftsText_title = "班次",
                model.situationText,
                situationText_title = "区域",
                model.departmentText,
                departmentText_title = "部门",
                model.observaDate,
                observaDate_title = "观察日期",
                model.evaluationText,
                evaluationText_title = "所有皆安全",
               
            }).ToList();

            var fileName = FILE_NAME_PREFIX + TempDirHelp.GetTimeStampFielName(".xlsx");


            return _excelHelp.Create(excelData);
        }
        public DateTime? getTime(DateTime? t, string type)
        {
            DateTime? dt = new DateTime();
            if (type == "b")
            {
                string str = t == null ? "" : ((DateTime)t).ToString("yyyy-MM-dd") + " 00:00:00";
                if (str != "")
                    dt = Convert.ToDateTime(str);
                else
                    dt = null;

            }
            else
            {
                string str = t == null ? "" : ((DateTime)t).ToString("yyyy-MM-dd") + " 23:59:59";
                if (str != "")
                    dt = Convert.ToDateTime(str);
                else
                    dt = null;
            }

            return dt;

        }


        public List<JG_STOPBigType> GetBigTypeList()
        {
            List<JG_STOPBigType> ret = new List<JG_STOPBigType>();

            ret = this._bigTypeRepository.QueryBase().ToList();

            return ret;
        }

        public List<JG_STOPSmallType> GetSmallTypeList()
        {
            List<JG_STOPSmallType> ret = new List<JG_STOPSmallType>();
            ret = this._smallTypeRepository.QueryBase().ToList();
            return ret;
        }

        public async Task<JG_STOPObserveDetailDto> InsertDetailAsync(JG_STOPObserveDetailDto dto, bool autoSave = true)
        {

            var entity = await _detailRepository.InsertAsync(Mapper.Map<JG_STOPObserveDetail>(dto), autoSave);
            return Mapper.Map<JG_STOPObserveDetailDto>(entity);

        }
        public async Task<JG_STOPObserveDetailDto> UpdateDetailAsync(JG_STOPObserveDetailDto dto, bool autoSave = true, List<string> noUpdateProperties = null)
        {
            var entity = await _detailRepository.UpdateAsync(Mapper.Map<JG_STOPObserveDetail>(dto), autoSave, noUpdateProperties);
            return Mapper.Map<JG_STOPObserveDetailDto>(entity);
        }

        public async Task<JG_STOPSmallType> InsertSmallTypeAsync(JG_STOPSmallType dto, bool autoSave = true)
        {
            return await _smallTypeRepository.InsertAsync(dto);

        }

        public List<JG_STOPObserveDetailDto> GetDetailList(Guid? mainId)
        {
            var ret = new List<JG_STOPObserveDetailDto>();
            var list =  _detailRepository.QueryBase().Where(x => x.STOPObserveMain == mainId).ToList();
            var smallTypes = _smallTypeRepository.QueryBase().ToList();
            foreach (var detail in list)
            {
                var dto = Mapper.Map<JG_STOPObserveDetailDto>(detail);
                dto.SmallTypeText = smallTypes.FirstOrDefault(x => x.SmallTypeCode == dto.SmallType)?.SmallTypeName;
                ret.Add(dto);
            }
            return ret;
        }
        public async Task DeleteDetailBatchAsync(Guid[] ids, bool autoSave = true)
        {
             await this._detailRepository.DeleteAsync(x => ids.Contains(x.Id));
        }
    }

}
